/*
 * Copyright 2006 George Georgovassilis <g.georgovassilis[at]gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gwtwidgets.server.spring.enhancer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.gwtwidgets.server.spring.GWTHandler;
import org.gwtwidgets.server.spring.GWTSpringController;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.SerializableException;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;


/**
 * Callback for CGLIB which determines wether the method invoked belongs to the
 * delegate object or the CGLIB-enhanced {@link GWTSpringController}. This
 * class is for internal use of the {@link GWTHandler}.
 * 
 * @author g.georgovassilis[at]gmail.com
 * 
 */
class DelegatingCallback implements MethodInterceptor {
	private RemoteService target;

	private Map/*<Method, Method>*/ methodsOnTarget = new HashMap/*<Method, Method>*/();

	private Map/*<Method, Method>*/ methodsOnExtendedClass = new HashMap/*<Method, Method>*/();

	private boolean unwrapExceptions;

	/**
	 * Wrap this callback around a service
	 * 
	 * @param target
	 * @param true
	 *            if you want {@link SerializableException} instances to be
	 *            unwrapped
	 */
	DelegatingCallback(RemoteService target, boolean unwrapExceptions) {
		this.target = target;
		this.unwrapExceptions = unwrapExceptions;
	}

	private synchronized Method getMethodToInvoke(Object target,
			Object[] arguments, Method prototypeMethod,
			Map/*<Method, Method>*/ lookup) {
		Method methodToInvoke = (Method) lookup.get(prototypeMethod);
		if (methodToInvoke != null)
			return methodToInvoke;
		Class targetClass = target.getClass();
		Class[] parameterTypes = prototypeMethod.getParameterTypes();
		String methodName = prototypeMethod.getName();

		try {
			methodToInvoke = targetClass.getMethod(methodName, parameterTypes);
			lookup.put(prototypeMethod, methodToInvoke);
			return methodToInvoke;
		} catch (Exception e) {
		}

		try {
			methodToInvoke = targetClass.getDeclaredMethod(methodName,
					parameterTypes);
			lookup.put(prototypeMethod, methodToInvoke);
			return methodToInvoke;
		} catch (Exception e) {
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	public Object intercept(Object obj, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		try {
			// Method cached on target?
			Method methodToInvoke = getMethodToInvoke(target, args, method,
					methodsOnTarget);
			if (methodToInvoke != null)
				return methodToInvoke.invoke(target, args);
			// Method cached on cglib'd class ?
			methodToInvoke = getMethodToInvoke(obj, args, method,
					methodsOnExtendedClass);
			if (methodToInvoke != null)
				return proxy.invokeSuper(obj, args);
		} catch (Throwable e) {
			if (!unwrapExceptions) throw e;
			Throwable cause = e;
			while (true){
				if (cause == null) throw e;
				if (cause instanceof SerializableException) throw cause;
				cause = cause.getCause();
			}
		}
		throw new NoSuchMethodException(method.getName() + " on "
				+ obj.getClass());

	}
}
